package com.htg.util;

import java.text.DecimalFormat;

public class UtilNumber {

    public static boolean isInteger(String str) {
        return str.matches("^[-+]?\\d+$");
    }

    public static boolean isFloat(String str) {
        return str.matches("^[-+]?\\d*\\.\\d+$");
    }

    public static boolean isDouble(String str) {
        return str.matches("^[-+]?\\d*\\.\\d+$");
    }

    public static boolean isNumber(String str) {
        return isInteger(str) || isFloat(str) || isDouble(str);
    }

    /**
     * 保留几位小数
     *
     * @param decimal 小数
     * @param amount  几位
     * @return
     */
    public static String holdDecimal(double decimal, int amount) {
        // 创建DecimalFormat对象，并设置保留小数位数的格式
        StringBuilder pattern = new StringBuilder("#.");
        //
        if (amount == 0) {
            pattern = new StringBuilder("#");
        } else {
            for (int i = 0; i < amount; i++) {
                pattern.append("0");
            }
        }

        //
        DecimalFormat df = new DecimalFormat(pattern.toString());
        String temp = df.format(decimal);
        return temp;
    }

    public static String holdDecimal2(double decimal,int amount){
        return String.format("%."+amount+"f",decimal);
    }
}
